﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace Kokomo.Controls
{
	public class LayoutFrame : Control
	{
		static LayoutFrame()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(LayoutFrame), new FrameworkPropertyMetadata(typeof(LayoutFrame)));
		}

		public FrameworkElement LayoutTarget
		{
			get { return (FrameworkElement)GetValue(LayoutTargetProperty); }
			set { SetValue(LayoutTargetProperty, value); }
		}

		// Using a DependencyProperty as the backing store for LayoutTarget.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty LayoutTargetProperty =
			LayoutHandle.LayoutTargetProperty.AddOwner(typeof(LayoutFrame), new UIPropertyMetadata(OnLayoutTargetChanged));

		private static void OnLayoutTargetChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
		{
			((LayoutFrame)target).OnLayoutTargetChanged(
				(FrameworkElement)e.OldValue,
				(FrameworkElement)e.NewValue
				);
		}
		protected virtual void OnLayoutTargetChanged(
			FrameworkElement oldTarget,
			FrameworkElement newTarget
			)
		{
			if (newTarget != null)
			{
				newTarget.LayoutUpdated += new EventHandler(newTarget_LayoutUpdated);
			}
			this.SyncLayoutWithTarget();
		}

		protected void SyncLayoutWithTarget()
		{
			FrameworkElement target = this.LayoutTarget;
			if (target != null)
			{
				Canvas.SetLeft(this, Canvas.GetLeft(target));
				Canvas.SetTop(this, Canvas.GetTop(target));
				this.Width = target.RenderSize.Width;
				this.Height = target.RenderSize.Height;
			}
		}

		void newTarget_LayoutUpdated(object sender, EventArgs e)
		{
			this.SyncLayoutWithTarget();
		}
	}
}
